package com.java;

/**
 * 守护线程
 */
public class DaemonThread {
    public static void main(String[] args) {
        System.out.println("主线程开始");

        Thread threadSon = new Thread(() -> {
            System.out.println("线程(" + Thread.currentThread().getName() + ")开始");

            System.out.println("线程(" + Thread.currentThread().getName() + ")运行中");
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("线程(" + Thread.currentThread().getName() + ")结束");
        });
        threadSon.setName("子线程");
        threadSon.start();

        Thread threadDaemon = new Thread(() -> {
            System.out.println("线程(" + Thread.currentThread().getName() + ")开始");

            System.out.println("线程(" + Thread.currentThread().getName() + ")运行中");
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("线程(" + Thread.currentThread().getName() + ")结束");
        });
        threadDaemon.setName("守护线程");
        threadDaemon.setDaemon(true); // ⭐⭐⭐
        threadDaemon.start();

        System.out.println("主线程结束");
    }

    /**
     * 输出结果如下，每次运行的结果不同！但"主线程开始"一定在最开始，"线程(守护线程)结束"未输出
     * 主线程开始
     * 线程(子线程)开始
     * 主线程结束
     * 线程(子线程)运行中
     * 线程(守护线程)开始
     * 线程(守护线程)运行中
     * 线程(子线程)结束
     */
}
